<template>
  <div class="partner-container">
    <!-- 搜索栏 -->
    <el-card class="search-container" shadow="never">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="合伙人名称">
          <el-input v-model="searchForm.keyword" placeholder="名称/手机号码" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable style="width: 180px">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="table-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>合伙人列表</span>
          <el-button type="primary" :icon="Plus" @click="openDialog('add')">添加合伙人</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="partnerList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="合伙人" min-width="180">
          <template #default="scope">
            <div class="partner-info">
              <el-avatar :size="40" :src="scope.row.avatar || defaultAvatar" />
              <div class="partner-details">
                <div class="partner-name">{{ scope.row.name }}</div>
                <div class="partner-phone">{{ scope.row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="company" label="公司" min-width="120" />
        <el-table-column prop="monthTarget" label="月均贷款额度(万元)" min-width="150" />
        <el-table-column prop="loanRate" label="放款利率化利率(%)" min-width="150" />
        <el-table-column prop="loanAmount" label="贷款最高额度(万元)" min-width="150" />
        <el-table-column label="企业形象" min-width="100">
          <template #default="scope">
            <el-button type="primary" link @click="previewImage(scope.row.companyImage)">
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="180">
          <template #default="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <div class="operation-btns">
              <el-button type="primary" size="small" @click="openDialog('edit', scope.row)">
                编辑
              </el-button>
              <el-button type="primary" size="small" @click="toggleStatus(scope.row)">
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 合伙人表单 -->
    <el-dialog v-model="dialogVisible" :title="formType === 'add' ? '添加合伙人' : '编辑合伙人'" width="650px" destroy-on-close>
      <el-form ref="partnerFormRef" :model="partnerForm" :rules="formRules" label-width="120px">
        <el-form-item label="合伙人名称" prop="name">
          <el-input v-model="partnerForm.name" placeholder="请输入合伙人名称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="partnerForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password" v-if="formType === 'add'">
          <el-input v-model="partnerForm.password" type="password" placeholder="请输入登录密码" show-password />
        </el-form-item>
        <el-form-item label="公司" prop="company">
          <el-input v-model="partnerForm.company" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="公司LOGO" prop="logo">
          <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
            :on-success="(res) => handleUploadSuccess(res, 'logo')" :before-upload="beforeAvatarUpload">
            <img v-if="partnerForm.logo" :src="partnerForm.logo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品类型" prop="productType">
          <el-select v-model="partnerForm.productType" placeholder="请选择产品类型" style="width: 100%">
            <el-option v-for="item in productTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否开户" prop="isOpened">
          <el-radio-group v-model="partnerForm.isOpened">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="月均贷款额度" prop="monthTarget">
          <el-input-number v-model="partnerForm.monthTarget" :min="0" :precision="2" style="width: 100%" />
          <div class="form-tip">单位: 万元</div>
        </el-form-item>
        <el-form-item label="放款时间周期" prop="loanPeriod">
          <el-input-number v-model="partnerForm.loanPeriod" :min="0" style="width: 100%" />
          <div class="form-tip">单位: 小时</div>
        </el-form-item>
        <el-form-item label="放款利率化利率" prop="loanRate">
          <el-input-number v-model="partnerForm.loanRate" :min="0" :precision="2" :step="0.01" style="width: 100%" />
          <div class="form-tip">单位: %</div>
        </el-form-item>
        <el-form-item label="贷款最高额度" prop="loanAmount">
          <el-input-number v-model="partnerForm.loanAmount" :min="0" :precision="2" style="width: 100%" />
          <div class="form-tip">单位: 万元</div>
        </el-form-item>
        <el-form-item label="服务项目" prop="services">
          <el-checkbox-group v-model="partnerForm.services">
            <el-checkbox label="一手渠道">一手渠道</el-checkbox>
            <el-checkbox label="微信接单">微信接单</el-checkbox>
            <el-checkbox label="保护渠道">保护渠道</el-checkbox>
            <el-checkbox label="土著业务">土著业务</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="贷款种类" prop="loanTypes">
          <el-checkbox-group v-model="partnerForm.loanTypes">
            <el-checkbox label="企业贷款">企业贷款</el-checkbox>
            <el-checkbox label="抵押贷款">抵押贷款</el-checkbox>
            <el-checkbox label="信用贷款">信用贷款</el-checkbox>
            <el-checkbox label="消费贷款">消费贷款</el-checkbox>
            <el-checkbox label="本店最新借贷">本店最新借贷</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="企业形象" prop="companyImage">
          <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
            :on-success="(res) => handleUploadSuccess(res, 'companyImage')" :before-upload="beforeAvatarUpload">
            <img v-if="partnerForm.companyImage" :src="partnerForm.companyImage" class="company-image" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="partnerForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="600px">
      <div class="image-preview-container">
        <img :src="previewImageUrl" class="preview-image" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Plus, Delete, Edit } from '@element-plus/icons-vue';

defineOptions({
  name: "Partners"
});

const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: ''
});

// 表格数据
const loading = ref(false);
const partnerList = ref([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框控制
const dialogVisible = ref(false);
const formType = ref('add');
const submitLoading = ref(false);
const partnerFormRef = ref();

// 图片预览
const previewVisible = ref(false);
const previewImageUrl = ref('');

// 产品类型选项
const productTypeOptions = [
  { label: '交易类', value: '交易类' },
  { label: '是否开户', value: '是否开户' }
];

// 表单数据
const partnerForm = reactive({
  id: null,
  name: '',
  phone: '',
  password: '',
  company: '',
  logo: '',
  productType: '',
  isOpened: 1,
  monthTarget: 0,
  loanPeriod: 0,
  loanRate: 0,
  loanAmount: 0,
  services: [],
  loanTypes: [],
  companyImage: '',
  status: 1,
  createTime: null
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入合伙人名称', trigger: 'blur' },
    { max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  logo: [
    { required: true, message: '请上传公司LOGO', trigger: 'change' }
  ],
  productType: [
    { required: true, message: '请选择产品类型', trigger: 'change' }
  ],
  services: [
    { type: 'array', required: true, message: '请选择至少一项服务项目', trigger: 'change' }
  ],
  loanTypes: [
    { type: 'array', required: true, message: '请选择至少一种贷款种类', trigger: 'change' }
  ],
  companyImage: [
    { required: true, message: '请上传企业形象', trigger: 'change' }
  ]
};

// 加载数据
const loadData = () => {
  loading.value = true;

  // 这里应该调用实际的API
  setTimeout(() => {
    // 模拟数据
    partnerList.value = [
      {
        id: 1,
        name: '张三',
        phone: '13812345678',
        avatar: '',
        company: '北京金融科技有限公司',
        logo: 'https://example.com/logo1.png',
        productType: '交易类',
        isOpened: 1,
        monthTarget: 500,
        loanPeriod: 24,
        loanRate: 4.5,
        loanAmount: 200,
        services: ['一手渠道', '微信接单', '保护渠道'],
        loanTypes: ['企业贷款', '抵押贷款'],
        companyImage: 'https://example.com/company1.jpg',
        status: 1,
        createTime: '2023-05-10 10:00:00'
      },
      {
        id: 2,
        name: '李四',
        phone: '13987654321',
        avatar: '',
        company: '上海融信贷款服务有限公司',
        logo: 'https://example.com/logo2.png',
        productType: '是否开户',
        isOpened: 0,
        monthTarget: 300,
        loanPeriod: 48,
        loanRate: 5.2,
        loanAmount: 150,
        services: ['微信接单', '土著业务'],
        loanTypes: ['消费贷款', '信用贷款'],
        companyImage: 'https://example.com/company2.jpg',
        status: 1,
        createTime: '2023-05-15 14:30:00'
      }
    ];
    pagination.total = 2;
    loading.value = false;
  }, 500);
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.status = '';
  handleSearch();
};

// 上传前检查
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('上传文件只能是图片格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 上传成功回调
const handleUploadSuccess = (res, field) => {
  // 实际项目中根据后端返回的数据结构进行处理
  partnerForm[field] = res.url || `https://example.com/${field}${Math.random()}.jpg`;
};

// 打开对话框
const openDialog = (type, row = null) => {
  formType.value = type;

  // 重置表单
  Object.assign(partnerForm, {
    id: null,
    name: '',
    phone: '',
    password: '',
    company: '',
    logo: '',
    productType: '',
    isOpened: 1,
    monthTarget: 0,
    loanPeriod: 0,
    loanRate: 0,
    loanAmount: 0,
    services: [],
    loanTypes: [],
    companyImage: '',
    status: 1,
    createTime: null
  });

  if (type === 'edit' && row) {
    // 编辑模式，填充数据
    Object.assign(partnerForm, row);
  }

  dialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  partnerFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true;

      // 这里应该调用实际的API
      setTimeout(() => {
        if (formType.value === 'add') {
          // 添加逻辑
          ElMessage.success('添加成功');
        } else {
          // 编辑逻辑
          ElMessage.success('编辑成功');
        }

        submitLoading.value = false;
        dialogVisible.value = false;
        loadData(); // 重新加载数据
      }, 500);
    }
  });
};

// 切换状态
const toggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const action = newStatus === 1 ? '启用' : '禁用';

  ElMessageBox.confirm(`确定要${action}该合伙人吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用实际的API
    row.status = newStatus;
    ElMessage.success(`${action}成功`);
  }).catch(() => { });
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该合伙人吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用实际的API
    const index = partnerList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      partnerList.value.splice(index, 1);
      pagination.total--;
      ElMessage.success('删除成功');
    }
  }).catch(() => { });
};

// 图片预览
const previewImage = (url) => {
  if (!url) {
    ElMessage.warning('暂无图片');
    return;
  }
  previewImageUrl.value = url;
  previewVisible.value = true;
};

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  loadData();
};

const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  loadData();
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.partner-info {
  display: flex;
  align-items: center;
}

.partner-details {
  margin-left: 10px;
}

.partner-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.partner-phone {
  color: #909399;
  font-size: 13px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.operation-btns {
  display: flex;
  gap: 8px;
  white-space: nowrap;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 150px;
  height: 150px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
  object-fit: cover;
}

.company-image {
  width: 150px;
  height: 150px;
  display: block;
  object-fit: cover;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.image-preview-container {
  display: flex;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 600px;
}
</style>